package interviewClassic150;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class RomanToInt {
    public int romanToInt(String s) {
        Map<Character,Integer> map = new HashMap<>();
        map.put('I',1);
        map.put('V',5);
        map.put('X',10);
        map.put('L',50);
        map.put('C',100);
        map.put('D',500);
        map.put('M',1000);

        char[] chars = s.toCharArray();
        int res = 0;
        int i = 0;
        while (i < chars.length) {
            Character cur = chars[i];
            Character next = null;
            if (i + 1 < chars.length) next = chars[i + 1];
            //下一个字符不为null
            if (next != null) {
                if ((cur.equals('I') && (next.equals('V') || next.equals('X')))
                        || (cur.equals('X') && (next.equals('L') || next.equals('C')))
                        || (cur.equals('C') && (next.equals('D') || next.equals('M')))
                ) {
                    //特殊情况处理
                    int curNum = map.get(next) - map.get(cur);
                    res += curNum;
                    i += 2;
                } else {
                    //非特殊情况，则只加当前值
                    int curNum = map.get(cur);
                    res += curNum;
                    i++;
                }
            } else {
                //当前是最后一个，只加当前值
                int curNum = map.get(cur);
                res += curNum;
                i++;
            }
        }

        return res;
    }

    @Test
    public void test() {
        String roman = "LVIII";
        int i = romanToInt(roman);
        System.out.println(i);
    }
}
